package il.ac.braude.sona.control;

import il.ac.braude.sona.constants.Mssg;
import il.ac.braude.sona.constants.P;
import il.ac.braude.sona.constants.Resources;
import il.ac.braude.sona.entities.LoginKit;
import il.ac.braude.sona.entities.User;
import il.ac.braude.sona.gui.forms.FormFrame;
import il.ac.braude.sona.gui.forms.FormListener;
import il.ac.braude.sona.gui.forms.myforms.LoginForm;
import il.ac.braude.sona.ocsf.client.Client;
import il.ac.braude.sona.ocsf.client.ServerResponseListener;

import java.util.ArrayList;
/**
 * The LoginController conatins methods to perform and view login 
 * 
 * @author  Ofek Ron
 * @author Avihay Avitan
 * @author Nitzan Inbar
 * @author Sasha Rozenthal
 * Laboratory in Software Engineering,Ort Braude College.</p>
 *
 */
public class LoginController implements FormListener {
	private LoginForm login;
	public static User user;
	private LoginKit userLoginKit;
	/**
	 * executes Login mechanism  - shows the users a form, 
	 * lets him submit his login info, 
	 * validates the login with the server synchronously
	 * lets user submit logins until he succeeds,
	 * when done, initiates a new MainMenuController.
	 */
	public void execLogin() {
		login = new LoginForm();
		login.addFormListener(this);
		login.showFrame();
		while (user==null) {
			synchronized(login) {
				try {
					login.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			} 
		}
		MainController mainMenu = new MainController();	
		mainMenu.execMainMenuForm(userLoginKit);
	}
	@Override
	public void onFormSubmited(final FormFrame formFrame, ArrayList<Object> values) {
		try {
			Client c = Client.getInstance();
			login.showMessege(Resources.Strings.Connecting);
			Mssg mssg = new Mssg(P.login,values);
			c.sendToServer(new ServerResponseListener() {


				@SuppressWarnings("unchecked")
				@Override
				public void onServerResponse(Mssg mssg) {
					if (mssg.is(P.error)) {
						login.showMessege((String) mssg.getMessege());
						return;
					}
					userLoginKit = (LoginKit)mssg.getMessege();
					user=userLoginKit.getUser();
					ArrayList<String> sys = ((LoginKit)mssg.getMessege()).getSystems();
					Resources.Strings.informationSystems=sys.toArray(new String[sys.size()]);
					synchronized(login) {
						login.notify();
					}
					formFrame.dispose();
					formFrame.dispose();
				}
			},mssg);
			 
		} catch (Exception e) {
			login.showMessege(Resources.Strings.ConnectFailed);
		}

	}
	public void execLoginForTesting(ArrayList<Object> values) {
		login = new LoginForm();
		onFormSubmited(login,values);
		while (user==null) {
			synchronized(login) {
				try {
					login.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			} 
		}
	}
	@Override
	public void onFormCanceled(FormFrame formFrame) {
		System.exit(0);
	}
	

}
